package casa.depesos.app.com.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

import casa.depesos.app.com.R;
import casa.depesos.app.com.databinding.ActivityTouchBinding;
import casa.depesos.app.com.frag.EmptyFragment;
import casa.depesos.app.com.frag.NetFailFragment;
import casa.depesos.app.com.http.BaseBean;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.RelationBean;
import casa.depesos.app.com.http.data.Relation;
import casa.depesos.app.com.http.req.RelationReq;
import casa.depesos.app.com.http.req.SaveTouchReq;
import casa.depesos.app.com.it.TextChangeListener;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class TouchActivity extends BaseInfoActivity {

    ActivityTouchBinding binding;
    List<Relation> list;
    int option;

    @Override
    public void getData() {
        showLoading();
        clearFragment(getSupportFragmentManager());
        new RelationReq().req(new ReqCallback<RelationBean>() {
            @Override
            public void callback(boolean success, RelationBean bean) {
                hideLoading();
                int type;
                if (success && bean.isValid()) {
                    type = 0;
                    list = bean.list;
                    option = 1;
                } else if (bean != null) {
                    type = 1;
                    option = 0;
                    list = new ArrayList<>();
                    list.add(new Relation());
                    list.add(new Relation());
                } else {
                    type = 2;
                }
                init(type);
            }
        });
    }

    final String title = "Información del contacto";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTouchBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (Constant.white || fromMe()) {
            if (fromMe()) {
                binding.bottom.setVisibility(View.GONE);
                binding.bg.setBackgroundResource(R.drawable.login_bg);

                int n = binding.linear.getChildCount();
                for (int i = 0; i < n; i++) {
                    View v = binding.linear.getChildAt(i);
                    v.setBackgroundResource(com.date.picker.R.drawable.white_round_bg2);
                }
                List<TextView> tmp = new ArrayList<>();
                tmp.add(binding.name);
                tmp.add(binding.phone);
                tmp.add(binding.relation);
                tmp.add(binding.name2);
                tmp.add(binding.phone2);
                tmp.add(binding.relation2);

                for (TextView v : tmp) {
                    v.setBackground(null);
                    v.setPadding(0, 0, 0, 0);
                    v.setTextSize(15);
                    v.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
                }
            } else {
                int n = binding.linear.getChildCount();
                int p = Utils.dp2Px(this, 15);
                for (int i = 0; i < n; i++) {
                    View v = binding.linear.getChildAt(i);
                    if (v instanceof LinearLayout) {
                        v.setPadding(p, p, p, 0);
                        ((ViewGroup.MarginLayoutParams) v.getLayoutParams()).topMargin = 0;
                    }
                }
            }
            binding.top1.getRoot().setVisibility(View.GONE);
            binding.top2.getRoot().setVisibility(View.VISIBLE);
            binding.top2.top.setPadding(0, Utils.getStatusBarHeight(this), 0, 0);
            binding.top2.back.setEnabled(true);
            binding.top2.back.setOnClickListener(view -> finish());
            binding.top2.title.setText(title);
            binding.getRoot().setBackgroundResource(R.color.bg2);
        } else {
            int n = binding.linear.getChildCount();
            int p = Utils.dp2Px(this, 15);
            for (int i = 0; i < n; i++) {
                View v = binding.linear.getChildAt(i);
                if (v instanceof LinearLayout) {
                    v.setPadding(p, p, p, 0);
                    ((ViewGroup.MarginLayoutParams) v.getLayoutParams()).topMargin = 0;
                }
            }
            initTop(binding.top1);
            binding.top2.getRoot().setVisibility(View.GONE);
        }
        Utils.setEditTextInputNoSpaceStart(binding.name, 50);
        Utils.setNumberEditTextInputSpace(binding.phone, 10);
        Utils.setEditTextInputNoSpaceStart(binding.name2, 50);
        Utils.setNumberEditTextInputSpace(binding.phone2, 10);

        Report.show("ACTION_KK_001");
        getData();
    }

    private void init(int type) {
        fail = false;
        if (type == 2) {
            fail = true;
            replaceFragment(R.id.frame, new NetFailFragment().setTitle(title));
            return;
        }
        if (type == 1 && fromMe()) {
            replaceFragment(R.id.frame, new EmptyFragment().setTitle(title));
            return;
        }
        binding.name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                list.get(0).name = editable.toString().trim();
                binding.nameErr.setVisibility(View.GONE);
                binding.name2Err.setVisibility(View.GONE);
                check();
            }
        });
        binding.name2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                list.get(1).name = editable.toString().trim();
                binding.nameErr.setVisibility(View.GONE);
                binding.name2Err.setVisibility(View.GONE);
                check();
            }
        });
        binding.phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                list.get(0).phone = editable.toString().trim();
                binding.phoneErr.setVisibility(View.GONE);
                binding.phone2Err.setVisibility(View.GONE);
                check();
            }
        });
        binding.phone2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                list.get(1).phone = editable.toString().trim();
                binding.phoneErr.setVisibility(View.GONE);
                binding.phone2Err.setVisibility(View.GONE);
                check();
            }
        });

        if (list.get(0).relation > 0) {
            binding.relation.setText(getResources().getStringArray(R.array.relation)[list.get(0).relation - 1]);
        }
        if (list.get(1).relation > 0) {
            binding.relation2.setText(getResources().getStringArray(R.array.relation)[list.get(1).relation - 1]);
        }
        if (!TextUtils.isEmpty(list.get(0).name)) {
            binding.name.setText(list.get(0).name);
        }
        if (!TextUtils.isEmpty(list.get(1).name)) {
            binding.name2.setText(list.get(1).name);
        }
        if (!TextUtils.isEmpty(list.get(0).phone)) {
            binding.phone.setText(list.get(0).phone);
        }
        if (!TextUtils.isEmpty(list.get(1).phone)) {
            binding.phone2.setText(list.get(1).phone);
        }
        binding.relation.setListener(new TextChangeListener() {
            @Override
            public void onTextChange(String txt, int index) {
                binding.rErr.setVisibility(View.GONE);
            }
        });
        binding.relation2.setListener(new TextChangeListener() {
            @Override
            public void onTextChange(String txt, int index) {
                binding.r2Err.setVisibility(View.GONE);
            }
        });
        chooseValue(binding.relation, R.array.relation, list.get(0), "relation", "Relación");
        chooseValue(binding.relation2, R.array.relation, list.get(1), "relation", "Relación");

        binding.next.setOnClickListener(view -> next());
    }

    private void hideAllErr() {
        binding.nameErr.setVisibility(View.GONE);
        binding.name2Err.setVisibility(View.GONE);
        binding.phoneErr.setVisibility(View.GONE);
        binding.phone2Err.setVisibility(View.GONE);
        binding.rErr.setVisibility(View.GONE);
        binding.r2Err.setVisibility(View.GONE);
    }

    private boolean isValidPhone(TextView tv, TextView err) {
        String s = tv.getText().toString().trim();
        if (s.length() != 10) {
            err.setVisibility(View.VISIBLE);
            err.setText(R.string.no_phone);
            return false;
        }
        return true;
    }

    private boolean isPhoneSameWithMe(String me, String now, TextView err) {
        if (TextUtils.equals(me, now)) {
            err.setVisibility(View.VISIBLE);
            err.setText(R.string.same_with_me);
            return true;
        }
        return false;
    }

    private boolean isValidName(String name, TextView err) {
        if (TextUtils.isEmpty(name)) {
            err.setVisibility(View.VISIBLE);
            err.setText(R.string.no_name);
            return false;
        }
        return true;
    }

    private void next() {
        Report.click("ACTION_KK_003");
        String phone1 = binding.phone.getText().toString().trim();
        String phone2 = binding.phone2.getText().toString().trim();
        String name1 = binding.name.getText().toString().trim();
        String name2 = binding.name2.getText().toString().trim();
        String phone = Utils.getPhone();
        hideAllErr();
        boolean valid = true;
        boolean bo1 = isValidPhone(binding.phone, binding.phoneErr);
        boolean bo2 = isValidPhone(binding.phone2, binding.phone2Err);
        if (bo1 && bo2) {
            bo1 = !isPhoneSameWithMe(phone, phone1, binding.phoneErr);
            bo2 = !isPhoneSameWithMe(phone, phone2, binding.phone2Err);
            if (bo1 && bo2) {
                if (TextUtils.equals(phone1, phone2)) {
                    valid = false;
                    binding.phoneErr.setVisibility(View.VISIBLE);
                    binding.phoneErr.setText(R.string.same_phone);
                    binding.phone2Err.setVisibility(View.VISIBLE);
                    binding.phone2Err.setText(R.string.same_phone);
                } else {
                    list.get(0).phone = phone1;
                    list.get(1).phone = phone2;
                }
            } else {
                valid = false;
            }
        } else {
            valid = false;
        }
        bo1 = isValidName(name1, binding.nameErr);
        bo2 = isValidName(name2, binding.name2Err);
        if (bo1 && bo2) {
            if (TextUtils.equals(name1, name2)) {
                valid = false;
                binding.nameErr.setVisibility(View.VISIBLE);
                binding.nameErr.setText(R.string.same_name);
                binding.name2Err.setVisibility(View.VISIBLE);
                binding.name2Err.setText(R.string.same_name);
            } else {
                list.get(0).name = name1;
                list.get(1).name = name2;
            }
        } else {
            valid = false;
        }
        if (TextUtils.isEmpty(binding.relation.getText().toString())) {
            valid = false;
            binding.rErr.setVisibility(View.VISIBLE);
        } else {
            binding.rErr.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(binding.relation2.getText().toString())) {
            valid = false;
            binding.r2Err.setVisibility(View.VISIBLE);
        } else {
            binding.r2Err.setVisibility(View.GONE);
        }
        if (!valid) {
            return;
        }
        showLoading();
        new SaveTouchReq(list, option).req(new ReqCallback() {
            @Override
            public void callback(boolean success, BaseBean bean) {
                hideLoading();
                if (Constant.white || success && bean.isValid()) {
                    if (getIntent().getIntExtra("from", 0) == 1) {
                        finish();
                        return;
                    }
                    if (Constant.white) {
                        Utils.setStatus(30);
                    }
                    Intent i = new Intent(TouchActivity.this, CardActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        });
    }

    @Override
    protected void check() {
        String phone1 = binding.phone.getText().toString().trim();
        String phone2 = binding.phone2.getText().toString().trim();
        String name1 = binding.name.getText().toString().trim();
        String name2 = binding.name2.getText().toString().trim();
        boolean bo = isEmpty(phone1, phone2, name1, name2);
        if (bo) {
            binding.next.setAlpha(0.6f);
        } else {
            if (phone1.length() != 10 || phone2.length() != 10) {
                binding.next.setAlpha(0.6f);
            } else {
                binding.next.setAlpha(1f);
            }
        }
    }

    public static boolean isEmpty(String... str) {
        for (String s : str) {
            if (TextUtils.isEmpty(s)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected int getIndex() {
        return 2;
    }
}
